package com.tarzan.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tarzan.api.model.request.menu.InsertMentReq;
import com.tarzan.api.model.request.menu.SysMenuReq;
import com.tarzan.api.model.request.menu.UpdateMentReq;
import com.tarzan.api.model.response.ment.MetaVo;
import com.tarzan.api.model.response.ment.RouterVo;
import com.tarzan.api.model.response.ment.SysMenuResp;
import com.tarzan.common.core.config.ConfigUtils;
import com.tarzan.common.core.exception.BusinessException;
import com.tarzan.common.core.exception.ErrorCodesEnum;
import com.tarzan.system.dao.SysMenuMapper;
import com.tarzan.system.entity.SysMenu;
import com.tarzan.system.entity.SysUser;
import com.tarzan.system.service.ISysMenuService;
import com.tarzan.system.service.ISysUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author liujinshan
 * @since 2020-07-09
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
    private final static Logger logger = LoggerFactory.getLogger(SysMenuServiceImpl.class);

    @Autowired
    private SysMenuMapper sysMenuMapper;


    @Autowired
    private ISysUserService iSysUserService;
/*
    @Autowired
    private RedisUitls redisUitls;*/


    String BEARER_TYPE = "Bearer ";
    /**
     * 根据用户id查询用户所拥有的菜单
     *
     * @param menu
     * @param userId
     * @return
     */
    @Override
    public List<SysMenuResp> selectMenuList(SysMenuReq menu, Long userId) {
        logger.debug("================>menu:"+menu.toString());
        String menuName = Optional.ofNullable(menu).map(SysMenuReq::getMenuName).orElse(null);
        List<SysMenuResp> menuList = null;
        if (1L == userId) {
            QueryWrapper queryWrapper = new QueryWrapper();
            if (null  != menuName) {
                queryWrapper.like("menu_name",menuName);
            }
            menuList = sysMenuMapper.selectList(queryWrapper);
        } else {
            menu.setUserId(userId);
            menuList = sysMenuMapper.selectMenuListByUserId(menu);
        }
        logger.debug("================>menuList:"+menuList.toString());
        return menuList;
    }

    /**
     * 查询菜单list
     * @param userId
     * @return java.util.List<com.jinshan.happy.vo.response.SysMenuResp>
     * @Date 2020/9/28 14:01
     * @Author liujinshan
     **/
    public List<SysMenuResp> selectMenuList(Long userId) {
        logger.debug("================>userId:"+userId);
        List<SysMenuResp> menuList = null;
        if (1L == userId) {
            menuList = sysMenuMapper.selectMenuTreeAll();
        } else {
            menuList = sysMenuMapper.selectMenuTreeByUserId(userId);
        }
        logger.debug("================>menuList:"+menuList);
        return getChildPerms(menuList,0);
    }
    /**
     * 构建前端路由所需要的菜单
     *
     * @param userName 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(String userName)
    {
        SysUser user = iSysUserService.findByuserName(userName);
        List<SysMenuResp> menus =  this.selectMenuList(user.getId());
        List<RouterVo> routers = buildMenus(menus);
        logger.info(routers.toString());
        return routers;
    }

    /**
     * 根据用户id查询菜单权限
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> selectMenuPermsByUserId(Long userId) {
        List<String> list = new ArrayList<>();
        /**
         * 判断如果用户为管理员则获取所有权限。
         */
        list = sysMenuMapper.selectMenuPermsByUserId(userId);
        return list;
    }

    /**
     * 根据ID查询菜单详情
     *
     * @param menuId
     * @return com.jinshan.happy.vo.response.SysMenuResp
     * @Date 2020/9/30 9:19
     * @Author liujinshan
     **/
    @Override
    public SysMenuResp findMenuDetailById(Long menuId) {
        SysMenuResp resp = new SysMenuResp();
        SysMenu s = sysMenuMapper.selectById(menuId);
        try{
            BeanUtils.copyProperties(s,resp);
        } catch (Exception e){
            throw new BusinessException(ErrorCodesEnum.JSON_CAST_ERROR.code(),ErrorCodesEnum.JSON_CAST_ERROR.msg());
        }
        return resp;
    }

    /**
     * 插入菜单
     *
     * @param insertMenuReq
     * @return void
     * @Date 2020/9/30 15:43
     * @Author liujinshan
     **/
    @Override
    public void insertMenu(InsertMentReq insertMenuReq) {
        SysMenu sysMenu = new SysMenu();
        try{
            BeanUtils.copyProperties(insertMenuReq,sysMenu);
        } catch (Exception e){
            throw new BusinessException(ErrorCodesEnum.JSON_CAST_ERROR.code(),ErrorCodesEnum.JSON_CAST_ERROR.msg());
        }
        sysMenuMapper.insert(sysMenu);
    }

    /**
     * 更新菜单
     *
     * @param updateMentReq
     * @return void
     * @Date 2020/9/30 15:52
     * @Author liujinshan
     **/
    @Override
    public void update(UpdateMentReq updateMentReq) {
        SysMenu sysMenu = new SysMenu();
        try{
            BeanUtils.copyProperties(updateMentReq,sysMenu);
        } catch (Exception e){
            throw new BusinessException(ErrorCodesEnum.JSON_CAST_ERROR.code(),ErrorCodesEnum.JSON_CAST_ERROR.msg());
        }
        try{
            sysMenuMapper.updateById(sysMenu);
        } catch (Exception e){
            throw new BusinessException(ErrorCodesEnum.JSON_CAST_ERROR.code(),ErrorCodesEnum.JSON_CAST_ERROR.msg());
        }
    }

    /**
     * 删除菜单，删除父菜单时同时删除子菜单。
     *
     * @param menuId
     * @return void
     * @Date 2020/10/9 8:50
     * @Author liujinshan
     **/
    @Override
    public void delete(Long menuId) {
        try{
            sysMenuMapper.deleteBatchMenu(menuId);
        } catch (Exception e){
            throw new BusinessException(ErrorCodesEnum.DELETE_MENU_ERROR.code(),ErrorCodesEnum.DELETE_MENU_ERROR.msg());
        }

    }

    /**
     * 退出登陆
     *
     * @param authHeader
     * @return void
     * @Date 2020/10/23 14:51
     * @Author liujinshan
     **/
    @Override
    public void removeLoginInfoByToken(String authHeader) {
        String tokenValue  =  authHeader.replace(BEARER_TYPE,StringUtils.EMPTY);/*
        redisUitls.del(tokenValue);*/
    }

    /**
     * 包装返回的菜单数据
     * @param menus
     * @return java.util.List<com.jinshan.happy.vo.response.RouterVo>
     * @Date 2020/9/28 14:02
     * @Author liujinshan
     **/
    public List<RouterVo> buildMenus(List<SysMenuResp> menus)
    {
        List<RouterVo> routers = new LinkedList<RouterVo>();

        for (SysMenuResp menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
            List<SysMenuResp> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && ConfigUtils.TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            else if (isMeunFrame(menu))
            {
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }



    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenuResp> getChildPerms(List<SysMenuResp> list, int parentId)
    {
        List<SysMenuResp> returnList = new ArrayList<SysMenuResp>();
        for (Iterator<SysMenuResp> iterator = list.iterator(); iterator.hasNext();)
        {
            SysMenuResp t = (SysMenuResp) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenuResp> list, SysMenuResp t)
    {
        // 得到子节点列表
        List<SysMenuResp> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenuResp tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                // 判断是否有子节点
                Iterator<SysMenuResp> it = childList.iterator();
                while (it.hasNext())
                {
                    SysMenuResp n = (SysMenuResp) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenuResp> list, SysMenuResp t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
    /**
     * 得到子节点列表
     */
    private List<SysMenuResp> getChildList(List<SysMenuResp> list, SysMenuResp t)
    {
        List<SysMenuResp> tlist = new ArrayList<SysMenuResp>();
        Iterator<SysMenuResp> it = list.iterator();
        while (it.hasNext())
        {
            SysMenuResp n = (SysMenuResp) it.next();
            if (n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenuResp menu)
    {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMeunFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenuResp menu)
    {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && ConfigUtils.TYPE_DIR.equals(menu.getMenuType())
                && ConfigUtils.NO_FRAME.equals(menu.getIsFrame()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMeunFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenuResp menu)
    {
        String component = ConfigUtils.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMeunFrame(menu))
        {
            component = menu.getComponent();
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMeunFrame(SysMenuResp menu)
    {
        return menu.getParentId().intValue() == 0 && ConfigUtils.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(ConfigUtils.NO_FRAME);
    }

}
